<template>
  <div ref="imageWrapper">
    <div class="head_box">
      <div class="left">
        <div class="tree_box">
          <j-ellipsis :value="queryParam.modelName" :length="9" class="ant-input" @click.native="showSelectModel" />
          <a-icon type="caret-down" />
          <!-- <a-input
            readOnly
            placeholder="点击选择"
            v-model="queryParam.modelName"
            @click.native="showSelectModel"
          ></a-input> -->
        </div>
      </div>
      <div
        v-if="problemStatus.length"
        :class="['problem', 'warn']"
        @click="
          () => {
            queryParam.modelId = modelId
            getSearchAndTitleList(modelId)
          }
        "
      >
        <a-tooltip
          :title="
            `疑似问题 ：${problemStatus.length && problemStatus[0] ? '超人员编制' : ''}${
              problemStatus.length && problemStatus[1] ? '，超经费预算' : ''
            }`
          "
          :overlayClassName="tooltipClass"
        >
          <a-icon type="exclamation-circle" /> 疑似问题？
        </a-tooltip>
      </div>
      <div class="right">
        <div
          class="item"
          v-for="item in modelList"
          :key="item.id"
          @click="
            () => {
              queryParam.modelId = item.id
              getSearchAndTitleList(item.id)
            }
          "
        >
          <div class="item_content">
            <div class="title">
              <j-ellipsis :value="item.modelName" :length="4" />
            </div>
            <div class="num">
              <j-ellipsis :value="item.extraNum" :length="25" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <a-card :bordered="false" style="margin-top:25px;border-radius:25px" v-if="tableShow">
      <h3 style="color:rgba(0,0,0,.6);float:left;line-height:30px">过滤条件</h3>
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24" type="flex" justify="end">
            <a-col v-for="(item, index) in listData" :key="index" :md="6" :sm="8">
              <a-form-item :label="item.fieldCnName">
                <div v-if="item.queryType === 'queryLike'">
                  <a-input v-model="item.queryValueStart"></a-input>
                </div>
                <div v-else-if="item.queryType === 'queryDate'">
                  <a-range-picker
                    v-model="dateArray"
                    style="width: 100%"
                    @change="
                      (value, dateString) => {
                        handlePanelChange(value, dateString, index)
                      }
                    "
                  />
                </div>
                <div v-else-if="item.queryType === 'queryCompare'">
                  <a-select style="width: 45%" placeholder="请选择" v-model="item.queryValueStart">
                    <a-select-option value=">">大于</a-select-option>
                    <a-select-option value="<">小于</a-select-option>
                    <a-select-option value="=">等于</a-select-option>
                    <a-select-option value=">=">大于等于</a-select-option>
                    <a-select-option value="<=">小于等于</a-select-option>
                  </a-select>
                  <a-input-number style="margin-left: 5%; width: 50%" v-model="item.queryValueEnd"></a-input-number>
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="2" :sm="2">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">过滤</a-button>
                <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">清除条件</a-button> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <span>实际支出</span>
      </div> -->

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <!-- <a @click="handleClickRow2(record)">关联</a>
          <a-divider type="vertical" /> -->
          <a style="color: red" @click="handleToYD(record)">转疑点</a>
        </span>
      </a-table>
    </a-card>
    <CheckOrganModal ref="departModal" @ok="updateQueryParam"></CheckOrganModal>
    <select-model ref="selectModel" @getSelectData="getSelectData"></select-model>
    <YDModel ref="YDModel" :routerData="$route.path" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import columns from './indexColumns'
import { httpAction, getAction, postAction, deleteAction } from '@/api/manage'
import moment from 'moment'
import CheckOrganModal from '../components/CheckOrganModal'
import SelectModel from './selectModel'
import { base64toImg } from '@/mixins/base64toImg'
import _ from 'lodash'
import YDModel from '@/views/sj/components/YDModel'

export default {
  name: 'ss',
  mixins: [JeecgListMixin, base64toImg],
  components: { CheckOrganModal, SelectModel, YDModel },
  data() {
    return {
      // 表头
      queryParam: {
        listData: '',
        modelName: '请点击选择数据模型'
      },
      // queryParam: {
      //   modelName: '点击选择'
      // },
      payload: {},
      listData: [],
      selectedData: '',
      radioValue: '',
      treeData: [],
      tableShow: false,
      rules: {
        accName: [{ required: true, message: '请选择账套' }]
      },
      columns: columns(this),
      url: {
        selectTree: '/dataModel/queryDataModelTemplate',
        list: '/dataModel/findResultList',
        getSearchAndTitle: '/dataModel/queryTitleAndSearch',
        yd: '/sjmx/queryModelMsg'
      },
      dataSource: [],
      dateArray: [],
      getListData: [],
      modelList: [],
      problemStatus: [],
      modelId: '',
      timeout: null,
      isQuery: false,
      disableMixinCreated: true
    }
  },
  watch: {
    $route: {
      handler: function(to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          console.log(to.query, 'to.query')
          this.isQuery = true
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.listData = JSON.parse(to.query.listData)
          const { proId, accCode } = this.queryParam
          const params = {
            id: data.modelId,
            extraId: proId || accCode,
            extraStartTime: this.queryParam.date ? this.queryParam.date[0] : undefined,
            extraEndTime: this.queryParam.date ? this.queryParam.date[1] : undefined
          }
          this.getChildModel(params, true)
          console.log(this.listData, 'this.listData')

          // this.$nextTick(() => {})
        }
      },
      immediate: true
    },
    modelList: {
      handler(val) {
        // console.log(val, 'val')
        if (val.length) {
          this.getWarnList(val)
        }
      }
    }
  },
  computed: {
    problemText() {},
    tooltipClass() {
      if (this.problemStatus.length) {
        return 'warn_tooltip warn'
      } else {
        return 'warn_tooltip success'
      }
    }
  },
  methods: {
    // TODO 查询
    searchReset() {
      this.dataSource = []
      this.dateArray = []
      this.listData = _.cloneDeep(this.getListData)
      this.queryParam = this.$options.data().queryParam
      this.ipagination = this.$options.data().ipagination
    },
    // TODO 查询
    getWarnList(val) {
      let i = 0
      this.problemStatus = []
      debugger
      for (let index = 0; index < val.length / 2; index++) {
        debugger
        if (+val[i].extraNum > +val[i + 1].extraNum) {
          this.problemStatus.push(true)
          i = i + 2
        }
      }
    },
    // 得到年份选择器的值
    handlePanelChange(value, dateString, index) {
      this.listData[index].queryValueStart = moment(value[0]).format('YYYY-MM-DD')
      this.listData[index].queryValueEnd = moment(value[1]).format('YYYY-MM-DD')
    },
    getSearchAndTitleList(id, flag = true) {
      // debugger
      this.listData = []
      this.dataSource = []
      this.columns = columns(this)
      getAction(this.url.getSearchAndTitle, { id: id }).then(res => {
        this.loading = false
        if (res.success) {
          this.tableShow = flag

          if (!this.isQuery) {
            res.result.searchList.splice(0, 3).map((item, index) => {
              this.listData.push({
                queryType: item.searchType,
                queryKey: item.fieldEnName,
                fieldCnName: item.fieldCnName,
                queryValueStart: '',
                queryValueEnd: ''
              })
            })

            this.queryParam.accCode ? this.addItem1() : this.addItem2()
          } else {
            let list = JSON.parse(this.$route.query.listData)
            list.splice(list.length - 2, 2)
            this.listData = list
          }

          this.getListData = _.cloneDeep(this.listData)

          res.result.titleList.map((item, index) => {
            this.columns.splice(index + 1, 0, {
              title: item.fieldCnName,
              align: 'center',
              dataIndex: item.fieldEnName
            })
          })
          this.loadData(1)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleToYD(record) {
      const { date = [], modelName = '' } = this.queryParam
      const { proId, accCode } = this.queryParam
      const params = {
        modelId: this.queryParam.modelId,
        unitId: proId || accCode,
        startTime: this.queryParam.date ? this.queryParam.date[0] : undefined,
        endTime: this.queryParam.date ? this.queryParam.date[1] : undefined
      }
      getAction(this.url.yd, params).then(res => {
        const { success, result, message } = res
        let ydnr, time
        let param = {
          ...this.queryParam,
          pModelId: this.modelId
        }
        if (success) {
          ydnr = result[0].gzzd
          time =
            result[0].ydms ||
            `${date.length ? `【${date[0] ? date[0] : ''}～${date[1] ? date[1] : ''}】` : ''}【${modelName}】`
        } else {
          time = `${date.length ? `【${date[0] ? date[0] : ''}～${date[1] ? date[1] : ''}】` : ''}【${modelName}】`
        }

        // 防抖
        if (this.timeout) {
          clearTimeout(this.timeout)
        }
        this.timeout = setTimeout(() => {
          this.addYd(param, ydnr, time)
        }, 500)
      })
    },
    addItem1() {
      return [
        {
          fieldCnName: '会计期间',
          queryKey: 'extraTime',
          queryType: 'queryDate',
          queryValueEnd: this.queryParam.date ? this.queryParam.date[1] : '',
          queryValueStart: this.queryParam.date ? this.queryParam.date[0] : ''
        },
        {
          fieldCnName: '账套id',
          queryKey: 'unitId',
          queryType: 'queryLike',
          queryValueEnd: '',
          queryValueStart: this.queryParam.unitId
        }
      ]
    },
    addItem2() {
      return [
        // {
        //   fieldCnName: '会计期间',
        //   queryKey: 'docDate',
        //   queryType: 'queryDate',
        //   queryValueEnd: this.queryParam.date ? this.queryParam.date[0] : '',
        //   queryValueStart: this.queryParam.date ? this.queryParam.date[1] : ''
        // },
        {
          fieldCnName: '项目id',
          queryKey: 'proId',
          queryType: 'queryLike',
          queryValueEnd: '',
          queryValueStart: this.queryParam.proId
        }
      ]
    },
    getChildModel(params, extraFlag = false) {
      getAction(this.url.selectTree, { ...params, extraFlag }).then(res => {
        if (res.success) {
          // console.log(res, 'res')
          this.modelList = res.result
          this.queryParam.modelId = res.result[0].id
          this.getSearchAndTitleList(res.result[0].id)
        }
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.queryParam.listData = JSON.stringify(
        _.cloneDeep(this.listData).concat(this.queryParam.accCode ? this.addItem1() : this.addItem2())
      )
      var params = this.getQueryParams() //查询条件
      console.log(params)
      this.loading = true
      postAction(this.url.list, params).then(res => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    // TODO～～～
    openSearchModel() {
      this.$refs.modalForm.edit()
      this.$refs.modalForm.isCheck = false
    },
    showSelectModel() {
      this.tableShow = false
      this.modelList = []
      this.dataSource = []
      if (Object.keys(this.queryParam).length > 0) {
        let data = _.cloneDeep(this.queryParam)
        this.$refs.selectModel.edit(data)
      } else {
        this.$refs.selectModel.edit(null)
      }
    },
    getSelectData(data) {
      this.queryParam = Object.assign({}, data)
      this.modelId = data.modelId
      const { proId, accCode, unitId } = this.queryParam
      const params = {
        id: data.modelId,
        extraId: proId || unitId,
        extraStartTime: this.queryParam.date ? this.queryParam.date[0] : undefined,
        extraEndTime: this.queryParam.date ? this.queryParam.date[1] : undefined
      }
      this.getChildModel(params, true)
      // this.getSearchAndTitleList(data.modelId)
    },
    // searchQuery() {
    //   this.$refs.form.validate(valid => {
    //     if (valid) {
    //       this.loadData(1)
    //     } else {
    //       return false
    //     }
    //   })
    // },
    updateQueryParam(data) {
      console.log(data, 'daat')
      let str1 = ''
      let str2 = ''
      data.map(item => {
        // TODO 账套～～～
        str1 += item.id + ','
        str2 += item.accName + ','
      })
      if (str1.length > 0) {
        str1 = str1.substr(0, str1.length - 1)
      }
      if (str2.length > 0) {
        str2 = str2.substr(0, str2.length - 1)
      }
      this.queryParam.accSetId = str1
      this.queryParam.accName = str2
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    handleAddSubmit(evt) {
      return new Promise((re, rj) => {
        postAction(this.url.add, evt).then(res => {
          if (res.success) {
            this.$refs.table.loadData()
            this.$message.success(res.message)
            re(res.success)
          } else {
            rj(res.success)
            this.$message.error(res.message)
          }
        })
      })
    },
    handleViewDetail(row) {
      this.$refs.detailModel.getPlanId(row)
      this.$refs.detailModel.visible = true
    }
  }
}
</script>
  <style scoped>
@import '~@assets/less/common.less';
</style>
<style lang="less">
.warn_tooltip {
  :global {
    .ant-tooltip-inner {
      // color: red;
      background-color: white;
    }
    .ant-tooltip-arrow::before {
      width: 10px;
      height: 10px;
      background-color: white;
    }
  }
}
.warn_tooltip.success {
  :global {
    .ant-tooltip-inner {
      color: #389e0d;
    }
  }
}
.warn_tooltip.warn {
  :global {
    .ant-tooltip-inner {
      color: red;
    }
  }
}
</style>

<style lang="less" scoped>
.head_box {
  height: 100px;
  background: url('~@assets/head_bg.png') no-repeat;
  background-size: 100% 100%;
  display: flex;
  position: relative;
  .left {
    flex: 1.5;
    align-self: center;
  }
  .problem {
    flex: 1;
    position: absolute;
    width: 150px;
    top: 50%;
    left: 25%;
    border-radius: 20px;
    cursor: pointer;
    box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.1);
    text-decoration: underline;
    padding: 10px 15px;
    transform: translateY(-50%);
    background-color: #fee5e6;
  }
  .warn {
    color: red;
  }
  .success {
    color: #389e0d;
  }
  .right {
    flex: 3;
    display: flex;
    // align-items: center;
    // justify-content: center;
    background: url('~@assets/head_r_bg.png') no-repeat;
    background-size: 99% 100%;
    position: relative;
    // padding: 0 8%;
    padding-left: 8%;
    .item {
      width: 0;
      max-width: 35%;
      height: 100%;
      flex: 1;
      background-position: center left;
      overflow: hidden;
      cursor: pointer;
      position: relative;
      display: flex;
      .item_content {
        background: url('~@assets/steps_item_bg.png') no-repeat;
        background-size: 100% 90%;
      }
      &:nth-last-of-type(1) {
        // flex: 1/2;
        background-size: 100% 90%;
        .item_content {
          // width: 100%;
        }
      }
      &:not(:nth-last-of-type(1))::after {
        content: '';
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        transform: translateY(-50%);
        border: 1px dashed #3955a6;
      }
      &_content {
        width: 50%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .title {
          font-size: 16px;
          color: #3955a6;
          font-weight: 600;
        }
        .num {
          font-size: 13px;
          color: orange;
          font-weight: bold;
        }
      }
    }
  }
}
.tree_box {
  margin-left: 65px;
  // margin-top: -10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  .anticon {
    color: #3955a6;
  }
  /deep/ .ant-input {
    background-color: transparent;
    border: none;
    box-shadow: none;
    height: 100%;
    width: 80%;
    color: #41518f;
    font-size: 30px;
    &::placeholder {
      font-size: 30px;
    }
  }
}
</style>